<template>
    <div>
        <div class="btn_group">
		    	<el-button type="primary" size="medium" @click="handleCreate">新建</el-button>
		    </div>
        <el-table :data="tableData" style="width: 100%" :row-style="{fontWeight: 600, textAlign: 'center'}" :cell-style="{textAlign: 'center'}" :header-cell-style="{textAlign: 'center'}"
        >
          <el-table-column prop="state" label="状态" width="100" />
          <el-table-column prop="b_name" label="名称" width="100" />
          <el-table-column prop="create_time" label="创建时间" width="200" />
          <el-table-column prop="detail" label="详细"  >
              <template #default="scope">
                  <div class="detail">
                      <div class="progress_wrapper">
                          <span class="title">对战进度:</span>
                          <div class="progress">
                              <el-progress :stroke-width="20" :text-inside="true" :show-text="scope.row.detail === 100" :indeterminate="scope.row.detail < 100" :percentage="scope.row.detail" :status="scope.row.status === '对战中' ? '' : 'success'" />
                          </div>
                      </div>
                      <el-button type="success" size="small" @click="handleDetail(scope.row)">详情</el-button>
                      <el-button type="primary" size="small" :disabled="scope.row.detail === 100 ? false : true" @click="handleStorage" >保存</el-button>
                      <el-button type="danger" size="small" @click="handleDeleteRow(scope.row.id)">删除</el-button>
                  </div>
              </template>
          </el-table-column>
        </el-table>
        <div class="block">
          <el-pagination layout="prev, pager, next" :total="10"></el-pagination>
        </div>
        <el-dialog
          v-model="dialogVisible"
          title="新增对战"
          width="50%"
          :before-close="handleClose"
        >
          <el-form ref="form" :model="form" :rules="rules" label-width="120px">
            <el-form-item label="对战名称">
              <el-input v-model="form.b_name" placeholder="请输入对战名称"></el-input>
            </el-form-item>
            <el-form-item label="环境">
              <el-select v-model="form.env" placeholder="请选择环境">
                <el-option v-for="(item, index) in envOptionsList" :key="index" :label="item[0]" :value="item[1]"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="模型1">
              <el-select v-model="form.model1" placeholder="请选择第一个模型">
                <el-option v-for="(item, index) in modelOptionsList" :key="index" :label="item" :value="item"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="模型2">
              <el-select v-model="form.model2" placeholder="请选择第二个模型">
                <el-option v-for="(item, index) in modelOptionsList" :key="index" :label="item" :value="item"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="最大步数" prop="step">
              <el-input v-model.number="form.step" placeholder="请输入最大步数"></el-input>
            </el-form-item>
          </el-form>
          <template #footer>
            <span class="dialog-footer">
              <el-button @click="dialogVisible = false">取消</el-button>
              <el-button type="primary" @click="handleConfirm"
                >确认</el-button
              >
            </span>
          </template>
        </el-dialog>
        <el-dialog
          v-model="detailDialog"
          title="详情"
          width="50%"
          :before-close="handleClose"
        >
          <h4>环境：{{detailData.env}}</h4>
          <h4>模型A：{{detailData.model1}}</h4>
          <h4>模型B：{{detailData.model2}}</h4>
          <h4>最大步数：{{detailData.step}}</h4>
          <template #footer>
            <span class="dialog-footer">
              <el-button type="primary" @click="detailDialog = false"
                >关闭</el-button
              >
            </span>
          </template>
        </el-dialog>
    </div>
</template>

<script>
import { ElMessage, ElMessageBox } from 'element-plus'
import * as vsApi from './api'
import * as envApi from '../env/api'
import * as modelApi from '../model/api'

export default {
  data () {
    const checkStep = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('请输入最大步数'))
      }
      setTimeout(() => {
        if (value < 1000) {
          callback(new Error('最大步数必须大于1000'))
        } else {
          callback()
        }
      }, 1000)
    }
    return {
      tableData: [],
      showSelect: false,
      dialogVisible: false,
      detailDialog: false,
      form: {
        env: '',
        model1: '',
        model2: '',
        step: '',
        b_name: ''
      },
      rules: {
        step: [{ validator: checkStep, trigger: 'blur' }]
      },
      envOptionsList: [],
      modelOptionsList: [],
      detailData: {}
    }
  },
  methods: {
    query () {
      vsApi.battleList().then(res => {
        this.tableData = res
      })
      envApi.battleList().then(res => {
        this.envOptionsList = res.map(item => [item.e_name, item.e_sort])
      })
      modelApi.battleList().then(res => {
        this.modelOptionsList = res.map(item => item.m_name)
      })
    },
    handleCreate () {
      this.dialogVisible = true
    },
    handleSelect () {
      this.showSelect = !this.showSelect
    },
    handleDelete () {
      this.tableData = this.tableData.filter(item => !this.multipleSelection.includes(item))
      this.showSelect = false
    },
    handleConfirm () {
      ElMessageBox.confirm(
        '是否确定新增',
        'Warning',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).then(() => {
        // 调用page_add方法请求服务端的新增页面接口
        vsApi.vs_add(this.form).then(res => {
          // 解析服务端响应内容
          if (res) {
            ElMessage({
              message: '提交成功',
              type: 'success'
            })
            this.query()
          } else {
            ElMessage({
              message: '提交失败',
              type: 'danger'
            })
          }
        })
        this.dialogVisible = false
        this.$nextTick(() => {
          console.log(this.tableData)
          this.createInterval()
        })
      })
    },
    handleClose (done) {
      done()
    },
    createInterval () {
      let timer = setInterval(() => {
        this.tableData[this.tableData.length - 1].detail += Math.floor(Math.random() * 10)
        if (this.tableData[this.tableData.length - 1].detail >= 100) {
          this.tableData[this.tableData.length - 1].detail = 100
          this.tableData[this.tableData.length - 1].state = '对战结束'
          vsApi.over(this.tableData[this.tableData.length - 1].id).then(res => {
            this.query()
          })
          clearInterval(timer)
          timer = null
        }
      }, 3000)
    },
    handleStorage () {
      let timer = setTimeout(() => {
        ElMessage({
          message: '保存成功',
          type: 'success'
        })
        timer && clearTimeout(timer)
        timer = null
      }, 2000)
    },
    handleDetail (data) {
      this.detailDialog = true
      this.detailData = data
    },
    handleDeleteRow (id) {
      console.log(id)
      ElMessageBox.confirm(
        '是否确定删除',
        'Warning',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).then(() => {
        vsApi.vs_del(id).then(res => {
          if (res) {
            ElMessage({
              message: '删除成功',
              type: 'success'
            })
            this.query()
          } else {
            ElMessage({
              message: '删除失败',
              type: 'danger'
            })
          }
        })
      })
    }
  },
  mounted () {
    this.query()
  },
  beforeUpdate () {
    this.$nextTick(() => {
      console.log(this.tableData)
      if (this.tableData.length > 0) {
        this.tableData.forEach(item => {
          let timer = setInterval(() => {
            item.detail += Math.floor(Math.random() * 10)
            if (item.detail >= 100) {
              item.detail = 100
              item.state = '对战结束'
              vsApi.over(item.id)
              clearInterval(timer)
              timer = null
            }
          }, 3000)
        })
      }
    })
  }
}
</script>

<style lang="scss" scoped>
    .block {
        position: absolute;
        right: 20px;
        margin-top: 30px;
    }
    .detail {
        display: flex;
        padding-left: 100px;
        align-items: center;
        .progress_wrapper{
            display: flex;
            .title {
                flex: 1;
                flex-shrink: 0;
            }
            .progress {
                width: 230px;
                margin-left: 10px;
            }
            margin-right: 80px;
        }
    }
    .el-table-column {
      transition: all 2s ease;
    }
    .el-select {
      display: block;
    }
</style>
